package site.lanmushan.framework.util.device;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Properties;

public class ToolOSInfo {
    /**
     * 系统分隔符
     */
    private static final String SYSTEM_SEPARATOR = File.separator;
    /**
     * Unix分隔符
     */
    private static final String UNIX_SEPARATOR = "/";

    /**
     * Windows分隔符字符
     */
    private static final String WINDOWS_SEPARATOR = "\\";

    public static void main(String[] args) {
        cpuInfo();
        getJvmInfo();
        getMemInfo();
        getSysFileInfo();
    }

    /**
     * <h5>功能:获取系统名称信息</h5>
     *
     * @return
     */
    public static String getOSName() {
        return System.getProperty("os.name").toLowerCase();
    }

    /**
     * <h5>功能:验证是否Linux系统</h5>
     *
     * @return
     */
    public static boolean isLinux(){
        return getOSName().indexOf("linux")>=0;
    }

    /**
     * <h5>功能:验证是否Linux系统</h5>
     *
     * @return
     */
    public static boolean isLinuxExt(){
        return SYSTEM_SEPARATOR.equals(UNIX_SEPARATOR);
    }

    /**
     * <h5>功能:验证是否Windows系统</h5>
     *
     * @return
     */
    public static boolean isWindows(){
        return getOSName().indexOf("windows")>=0;
    }

    /**
     * <h5>功能:验证是否Windows系统</h5>
     *
     * @return
     */
    public static boolean isWindowsExt(){
        return SYSTEM_SEPARATOR.equals(WINDOWS_SEPARATOR);
    }

    /**
     * <h5>功能:获取系统CPU信息</h5>
     *
     */
    public static void cpuInfo() {
        JSONObject cpuInfo = new JSONObject();

        SystemInfo systemInfo = new SystemInfo();
        // 获取硬件信息
        HardwareAbstractionLayer hardware = systemInfo.getHardware();
        // 获取处理器信息
        CentralProcessor processor = hardware.getProcessor();
        // 获取CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        long[] ticks = processor.getSystemCpuLoadTicks();

        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

        //cpu核数
        cpuInfo.put("cpuNum-核数", processor.getLogicalProcessorCount());
        cpuInfo.put("cpu标识",processor.getProcessorIdentifier());
        //cpu系统使用率
        cpuInfo.put("cSys-系统使用率", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        //cpu用户使用率
        cpuInfo.put("user-用户使用率", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        //cpu当前等待率
        cpuInfo.put("iowait-当前等待率", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        //cpu当前使用率
        cpuInfo.put("idle-当前使用率", new DecimalFormat("#.##%").format(1.0 - (idle * 1.0 / totalCpu)));

        System.out.println(cpuInfo.toJSONString());
    }

    /**
     * <h5>功能:获取系统JVM信息</h5>
     *
     * @return
     */
    public static JSONObject getJvmInfo() {
        JSONObject jvmInfo = new JSONObject();
        Properties props = System.getProperties();
        Runtime runtime = Runtime.getRuntime();
        long jvmTotalMemoryByte = runtime.totalMemory();
        long freeMemoryByte = runtime.freeMemory();
        //jvm总内存
        jvmInfo.put("total-jvm总内存", formatByte(runtime.totalMemory()));
        //空闲空间
        jvmInfo.put("free-空闲空间", formatByte(runtime.freeMemory()));
        //jvm最大可申请
        jvmInfo.put("max-jvm最大可申请", formatByte(runtime.maxMemory()));
        //vm已使用内存
        jvmInfo.put("user-vm已使用内存", formatByte(jvmTotalMemoryByte - freeMemoryByte));
        //jvm内存使用率
        jvmInfo.put("usageRate-jvm内存使用率", new DecimalFormat("#.##%").format((jvmTotalMemoryByte - freeMemoryByte) * 1.0 / jvmTotalMemoryByte));
        //jdk版本
        jvmInfo.put("jdkVersion-jdk版本", props.getProperty("java.version"));
        //jdk路径
        jvmInfo.put("jdkHome-jdk路径", props.getProperty("java.home"));

        System.out.println(jvmInfo.toJSONString());
        return jvmInfo;
    }

    /**
     * <h5>功能:获取系统内存信息</h5>
     *
     * @return
     */
    public static JSONObject getMemInfo() {
        JSONObject memInfo = new JSONObject();

        SystemInfo systemInfo = new SystemInfo();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //总内存
        long totalByte = memory.getTotal();
        //剩余
        long acaliableByte = memory.getAvailable();
        //总内存
        memInfo.put("total-总内存", formatByte(totalByte));
        //已用内存
        memInfo.put("used-已用内存", formatByte(totalByte - acaliableByte));
        //剩余内存
        memInfo.put("free-剩余内存", formatByte(acaliableByte));
        //使用率
        memInfo.put("usageRate-使用率", new DecimalFormat("#.##%").format((totalByte - acaliableByte) * 1.0 / totalByte));

        System.out.println(memInfo.toJSONString());
        return memInfo;
    }

    /**
     * <h5>功能:获取系统盘符信息</h5>
     *
     * @return
     */
    public static JSONArray getSysFileInfo() {
        JSONObject sysFileInfo;
        JSONArray sysFiles = new JSONArray();
        SystemInfo systemInfo = new SystemInfo();
        OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
        FileSystem fileSystem = operatingSystem.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            sysFileInfo = new JSONObject();
            //盘符路径
            sysFileInfo.put("dirName-盘符路径", fs.getMount());
            //总大小
            sysFileInfo.put("total-总大小", formatByte(fs.getTotalSpace()));
            //剩余大小
            sysFileInfo.put("free-剩余大小", formatByte(fs.getUsableSpace()));
            //已经使用量
            sysFileInfo.put("used-已经使用量", formatByte(fs.getTotalSpace() - fs.getUsableSpace()));
            //盘符类型
            sysFileInfo.put("sysTypeName-盘符类型", fs.getType());
            //文件类型
            sysFileInfo.put("typeName-文件类型", fs.getName());
            if (fs.getTotalSpace() == 0) {
                //资源的使用率
                sysFileInfo.put("usage-资源的使用率", 0);
            } else {
                sysFileInfo.put("usage-资源的使用率",new DecimalFormat("#.##%").format((fs.getTotalSpace() - fs.getUsableSpace()) * 1.0 / fs.getTotalSpace()));
            }
            sysFiles.add(sysFileInfo);
            System.out.println(sysFileInfo.toJSONString());
        }

        return sysFiles;
    }

    // =================== private method ===================

    /**
     * 单位转换
     */
    private static String formatByte(long byteNumber) {
        //换算单位
        double FORMAT = 1024.0;
        double kbNumber = byteNumber / FORMAT;
        if (kbNumber < FORMAT) {
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber / FORMAT;
        if (mbNumber < FORMAT) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / FORMAT;
        if (gbNumber < FORMAT) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }

}
